import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-05-27
 * Time: 18:36
 */
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    // 用于保存所有的留言
    //private List<Message> messages=new ArrayList<>();
    // 用于转换 JSON 字符串
    private ObjectMapper objectMapper = new ObjectMapper();
    //private String filePath = "d:/messages.txt";
    private List<Message> load() throws SQLException {
        // 通过 jdbc, 从数据库读取出数据
        // 1. 创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/confession_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("12345");
        // 2. 建立连接
        Connection connection = dataSource.getConnection();
        // 3. 构造 SQL
        String sql = "select * from confession";
        PreparedStatement statement = connection.prepareStatement(sql);
        // 4. 执行 SQL
        ResultSet resultSet = statement.executeQuery();
        // 5. 遍历结果集合
        List<Message> messageList = new ArrayList<>();
        while (resultSet.next()) {
            Message message = new Message();
            message.from = resultSet.getString("from_me");
            message.to = resultSet.getString("to_you");
            message.message = resultSet.getString("message");
            messageList.add(message);
        }
        // 6. 关闭连接释放资源
        resultSet.close();
        statement.close();
        connection.close();
        return messageList;
    }


    private void save(Message message) throws SQLException {
        // 通过 jdbc, 往数据库中存一个数据.
        // 1. 创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/confession_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("12345");
        // 2. 建立连接
        Connection connection = dataSource.getConnection();
        // 3. 构造 SQL
        String sql = "insert into confession values(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, message.from);
        statement.setString(2, message.to);
        statement.setString(3, message.message);
        // 4. 执行 SQL
        statement.executeUpdate();
        // 5. 释放资源, 关闭连接
        statement.close();
        connection.close();
    }
    /*public List<Message> load() {
        List<Message> messages = new ArrayList<>();
        System.out.println("从文件读取数据");
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
            while (true) {
                String line = bufferedReader.readLine();
                if (line == null) {
                    break;
                }
                String[] tokens = line.split("\t");
                Message message = new Message();
                message.from = tokens[0];
                message.to = tokens[1];
                message.message = tokens[2];
                messages.add(message);
            }
        } catch (IOException e) {
// 首次运行的时候文件不存在, 可能会在这里触发异常.
            e.printStackTrace();
        }
        System.out.println("共读取数据 " + messages.size() + " 条!");
        return messages;
    }*/
    
    /*public void save(Message message) {
    System.out.println("向文件写入数据");
    // 使用追加写的方式打开文件
    try (FileWriter fileWriter = new FileWriter(filePath, true)) {
      fileWriter.write(message.from + "\t" + message.to + "\t" + message.message + "\n");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }*/

    // 获取所有留言
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Message> messages = null;
        try {
            messages = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.setContentType(("application/json;charset=utf-8"));
        String string = objectMapper.writeValueAsString(messages);
        resp.getWriter().write(string);
        System.out.println("get  ok");
    }

    // 新增留言
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(("application/json;charset=utf-8"));
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        try {
            save(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.getWriter().write(("{ \"ok\": 1 }"));
        System.out.println("post ok");
    }
}
